package product

import (
	"FinancialManagement/src/base/baselog"
	"FinancialManagement/src/base/db"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// CreateProductInfo
// @Description: 创建产品信息
// @receiver productInfo
// @return error
func (productInfo *ProductModel) CreateProductInfo() error {
	return db.Res.DB.GetDbW().Create(productInfo).Error
}

// GetProductInfo
// @Description: 获取指定产品信息
// @param typeID 库存类型编号
// @return *ProductModel
// @return error
func GetProductInfo(typeID int) (*ProductModel, error) {
	var productInfo ProductModel
	result := db.Res.DB.GetDbW().First(&productInfo, typeID)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("product not found")
	}
	return &productInfo, result.Error
}

// UpdateProductInfo
// @Description: 修改产品信息
// @receiver productInfo
// @return error
func (productInfo *ProductModel) UpdateProductInfo() error {
	result := db.Res.DB.GetDbW().Save(&productInfo)
	return result.Error
}

// DeleteProductInfo
// @Description: 删除指定产品信息
// @param typeID
// @return error
func DeleteProductInfo(productId int) error {
	baselog.Logger.Info("删除产品", zap.Int("productId", productId))
	sqlCount := fmt.Sprintf("select count(*) from sales_detail_item where product_id=%d", productId)
	count := 0
	err := db.Res.DB.GetDbR().Raw(sqlCount).Row().Scan(&count)
	if err != nil {
		return errors.New("product not found")
	} else {
		if count > 0 {
			return errors.New("当前产品在使用，无法删除")
		}
	}
	result := db.Res.DB.GetDbW().Delete(&ProductModel{}, productId)
	return result.Error
}

// GetProductList
// @Description: 获取产品列表，分页
// @param productName
// @param pageSize
// @param pageNumber
// @return products
// @return count
// @return err
func GetProductList(productName string, pageSize, pageNumber int) (products []ProductModel, count int64, err error) {
	sqlWhere := " 1=1 "
	if productName != "" {
		sqlWhere = fmt.Sprintf("%s and product_name like '%%%s%%'", sqlWhere, productName)
	} // 计算起始行
	startPage := (pageNumber - 1) * pageSize
	result := db.Res.DB.GetDbR().Model(&ProductModel{}).Where(sqlWhere).Order("product_id").Limit(pageSize).Offset(startPage).Find(&products).Count(&count)
	return products, count, result.Error
}

// GetProductListAll
// @Description: 获取所有产品信息
// @param productName
// @return products
// @return err
func GetProductListAll(productName string) (products []ProductModel, err error) {
	sqlWhere := " 1=1 "
	if productName != "" {
		sqlWhere = fmt.Sprintf("%s and product_name like '%%%s%%'", sqlWhere, productName)
	}
	result := db.Res.DB.GetDbR().Model(&ProductModel{}).Where(sqlWhere).Find(&products)
	return products, result.Error
}

// GetProductListForPurchaseId
// @Description: 获取采购单对应的产品信息
// @param purchaseId
// @return products
// @return err
func GetProductListForPurchaseId(purchaseId int) (products []ProductModel, err error) {
	sql := fmt.Sprintf("SELECT pdi.product_id,SUM(actual_amount)/SUM(quantity) as cbdj,pt.product_name,pt.product_describe FROM purchase_detail_item as pdi LEFT JOIN product as pt ON pt.product_id=pdi.product_id WHERE pdi.purchase_id=%d GROUP BY pdi.product_id",
		purchaseId)
    res, err := db.Res.DB.GetDbR().Raw(sql).Rows()
    if err != nil {
        return nil, err
    }
    defer res.Close()
    for res.Next() {
        var product ProductModel
        err = res.Scan(&product.ProductId, &product.Cbdj, &product.ProductName, &product.ProductDesc)
        if err != nil {
            baselog.Logger.Error("解析错误", zap.Error(err))
            continue
        }
        products = append(products, product)
    }
    return products, nil
}
